<template>
  <div>
    <common-layout>
      <div class="top" style="padding-top: 8%;">
        <div class="header">
          <img alt="logo" class="logo" src="@/assets/img/logo.png" />
          <span class="title">{{systemName}}</span>
        </div>
        <div class="desc">{{systemDesc}}</div>
      </div>
      <div class="login">
        <a-form-model :model="form" ref="form">
            <div>
              <a-alert type="error" :closable="true" v-if="error" :message="error" @close='onClose' showIcon style="margin-bottom: 24px;" />
              <a-form-model-item prop="username" required>
                <a-input
                  v-model="form.username"
                  size="large"
                  autocomplete
                  :placeholder="$t('title.username')"
                >
                  <a-icon slot="prefix" type="user" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item prop="password" required>
                <a-input-password 
                  v-model="form.password"
                  size="large"
                  autocomplete
                  :placeholder="$t('title.password')"
                >
                  <a-icon slot="prefix" type="lock" />
                </a-input-password >
              </a-form-model-item>
            </div>
          <div>
            <a-checkbox @change="rememberMeChange" :checked="rememberMe">{{$t('title.rememberMe')}}</a-checkbox>
            <select-lang style="float: right;"></select-lang>
          </div>
          <a-form-model-item>
            <a-button :loading="logging" style="width: 100%;margin-top: 24px" size="large" htmlType="submit" type="primary" @click="onSubmit">{{$t('btn.login')}}</a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
    </common-layout>
    <ul class="square-anim">
			<li v-for="index of 10" :key="index"/>
		</ul>
  </div>
</template>

<script>
import CommonLayout from '@/layouts/common-layout'
import SelectLang from '@/components/lang/select-lang'
import {accountService} from '@/services'
import {setAuthorization} from '@/utils/request'
import {loadRoutes} from '@/utils/router-util'
import {mapMutations} from 'vuex'
import "@/theme/square-anim.less"

export default {
  name: 'Login',
  i18n: require('./i18n'),
  components: {
    CommonLayout,
    SelectLang
  },
  data () {
    return {
      logging: false,
      error: '',
      rememberMe: false,
      form: {
        username: undefined,
        password: undefined
      },
      securityPwd: undefined
    }
  },
  computed: {
    systemName () {
      return this.$t(this.$store.state.setting.systemName)
    },
    systemDesc () {
      return this.$t(this.$store.state.setting.systemDesc)
    }
  },
  methods: {
    ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles']),
    onSubmit (e) {
      e.preventDefault()
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.logging = true
          // 密码进行MD5加密
          this.securityPwd = this.$md5(this.form.password)
          accountService.login(JSON.stringify({
            username: this.form.username,
            password: this.securityPwd
          })).then(this.afterLogin).finally(() => this.logging = false)
        }
      })
    },
    afterLogin(res) {
      const loginRes = res.data
      if (loginRes.code === 200) {
        const {token, nickname, avatar, roleInfos, permissionInfos} = loginRes.data
        this.setUser({
          name: nickname,
          avatar: avatar
        })
        this.setRoles(roleInfos)
        this.setPermissions(permissionInfos)
        setAuthorization({token: token})

        if (this.rememberMe) {
          // 保存用户名密码到localstorage
          localStorage.setItem('username', this.form.username)
          localStorage.setItem('password', this.form.password)
        }
        else {
          // 清除localstorage中的用户名密码
          localStorage.removeItem('username')
          localStorage.removeItem('password')
        }

        // 获取路由配置
        accountService.getRoutes().then(result => {
          const routes = result.data.data
          loadRoutes(routes)
          this.$router.push('/')
          this.$message.success('欢迎回来 ' + nickname)
        })

      } else {
        this.error = loginRes.msg
      }
    },
    onClose() {
      this.error = false
    },
    rememberMeChange(e) {
      this.rememberMe = e.target.checked
    }
  },
  mounted() {
    // 清理Tabs缓存
    sessionStorage.setItem(process.env.VUE_APP_TBAS_KEY, null)
    let username = localStorage.getItem('username')
    let password = localStorage.getItem('password')
    if (username && password) {
      this.form = {
         'username': username,
         'password': password
      }
      this.rememberMe = true
    }
  }
}
</script>

<style lang="less" scoped>
.common-layout{
    .top {
      text-align: center;
      .header {
        height: 44px;
        line-height: 44px;
        a {
          text-decoration: none;
        }
        .logo {
          height: 44px;
          vertical-align: top;
          margin-right: 16px;
        }
        .title {
          font-size: 33px;
          color: @title-color;
          font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
          font-weight: 600;
          position: relative;
          top: 2px;
        }
      }
      .desc {
        font-size: 14px;
        color: @text-color-second;
        margin-top: 12px;
        margin-bottom: 40px;
      }
    }
    .login{
      width: 368px;
      margin: 0 auto;
      @media screen and (max-width: 576px) {
        width: 95%;
      }
      @media screen and (max-width: 320px) {
        .captcha-button{
          font-size: 14px;
        }
      }
      .icon {
        font-size: 24px;
        color: @text-color-second;
        margin-left: 16px;
        vertical-align: middle;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: @primary-color;
        }
      }
    }
  }
</style>
